﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using DataAccess;
using System.Runtime.InteropServices;
using System.IO;
using MySql.Data.MySqlClient;
namespace SMSSendServer
{
    public partial class SMSSendServer : ServiceBase
    {
        public SMSSendServer()
        {
            InitializeComponent();
        }
        public int socket;


        [DllImport("smsdll.dll",
               EntryPoint = "App_SetIniPath",
               CharSet = CharSet.Ansi,
               CallingConvention = CallingConvention.StdCall)]
        public static extern int App_SetIniPath(string fPath);

        [DllImport("smsdll.dll",
               EntryPoint = "App_Bind",
               CharSet = CharSet.Ansi,
               CallingConvention = CallingConvention.StdCall)]
        public static extern int App_Bind();

        [DllImport("smsdll.dll",
              EntryPoint = "App_Unbind",
               CharSet = CharSet.Ansi,
               CallingConvention = CallingConvention.StdCall)]
        public static extern int App_Unbind();


        [DllImport("smsdll.dll",
             EntryPoint = "App_Deliver",
               CharSet = CharSet.Ansi,
               CallingConvention = CallingConvention.StdCall)]
        public static extern int App_Deliver(StringBuilder Src_Id, StringBuilder Dest_Id, StringBuilder Msg_Content);



        [DllImport("smsdll.dll",
             EntryPoint = "App_Submit",
             CharSet = CharSet.Ansi,//Unicode,
          CallingConvention = CallingConvention.Cdecl)]//Cdecl
        //unsafe public static extern int App_Submit(char* service_id, char* dest_terminal_id, char* content);
        public static extern int App_Submit(string service_id, string dest_terminal_id, string src_id, string content);



        [DllImport("smsdll.dll",
             EntryPoint = "App_report",
               CharSet = CharSet.Ansi,
               CallingConvention = CallingConvention.StdCall)]
        public static extern int App_report(StringBuilder msgid, StringBuilder resultpS);

        [DllImport("smsdll.dll",
                  EntryPoint = "App_Gateway_Resp",
                    CharSet = CharSet.Ansi,
                    CallingConvention = CallingConvention.StdCall)]
        public static extern int App_Gateway_Resp(StringBuilder msgid, StringBuilder gateway_resp);

        [DllImport("smsdll.dll",
          EntryPoint = "App_ActiveTest",
            CharSet = CharSet.Ansi,
            CallingConvention = CallingConvention.StdCall)]
        public static extern int App_ActiveTest(StringBuilder active_resp);
        /*****************************************************************
         # Function: 
                int App_Bind()
         # Explain:
                与服务器建立连接
         # Description:
                getcfg(); 获取配置文件中的连接参数(IP,username,password,port)
                bind_service: 与服务器建立socket连接
                连接成功以后,初始化收,发,状态报告队列,创建收发线程
         # return :
                  1          成功;
                  2          socket连接已经存在
                 -100      打开配置文件失败,请确认路径是否是英文路径;
                 -111      建立socket连接通道失败,请确认网络是否正常
                 -112      connect bind服务器失败,请确认IP和端口是否正确
                 -113      command_id 或消息长度错误
                 -114      BIND认证不成功,请确认用户名和密码是否正确
                 -115      发送bind包失败
                 -2    bind失败 		
        *****************************************************************/
        protected override void OnStart(string[] args)
        {
            SendSMS msm = new SendSMS();
            MySqlDataReader ds = msm.GetList(DateTime.Now);
           while(ds.Read())
           {
                    string username = ds["MappedChar"].ToString();
                    string PhoneNumber = ds["TelPhone"].ToString();
                    SendSMS sm = new SendSMS(username, PhoneNumber);
                    Thread th = new Thread(new ThreadStart(sm.Send));
                    th.Start();
                    Thread.Sleep(3000);
           }
           StopServer("SMSSendServer");
        }
        public void StopServer(string Pname)
        {
            Process[] MyProcess = Process.
            GetProcessesByName(Pname);
            MyProcess[0].Kill();

        }
        protected override void OnStop()
        {
            StreamWriter sw = File.AppendText(@"D:\test.txt");
            sw.WriteLine("服务停止");
            sw.Close();
        }
    }
    public class SendSMS
    {
        public int socket;


        [DllImport("smsdll.dll",
               EntryPoint = "App_SetIniPath",
               CharSet = CharSet.Ansi,
               CallingConvention = CallingConvention.StdCall)]
        public static extern int App_SetIniPath(string fPath);

        [DllImport("smsdll.dll",
               EntryPoint = "App_Bind",
               CharSet = CharSet.Ansi,
               CallingConvention = CallingConvention.StdCall)]
        public static extern int App_Bind();

        [DllImport("smsdll.dll",
              EntryPoint = "App_Unbind",
               CharSet = CharSet.Ansi,
               CallingConvention = CallingConvention.StdCall)]
        public static extern int App_Unbind();


        [DllImport("smsdll.dll",
             EntryPoint = "App_Deliver",
               CharSet = CharSet.Ansi,
               CallingConvention = CallingConvention.StdCall)]
        public static extern int App_Deliver(StringBuilder Src_Id, StringBuilder Dest_Id, StringBuilder Msg_Content);



        [DllImport("smsdll.dll",
             EntryPoint = "App_Submit",
             CharSet = CharSet.Ansi,//Unicode,
          CallingConvention = CallingConvention.Cdecl)]//Cdecl
        //unsafe public static extern int App_Submit(char* service_id, char* dest_terminal_id, char* content);
        public static extern int App_Submit(string service_id, string dest_terminal_id, string src_id, string content);



        [DllImport("smsdll.dll",
             EntryPoint = "App_report",
               CharSet = CharSet.Ansi,
               CallingConvention = CallingConvention.StdCall)]
        public static extern int App_report(StringBuilder msgid, StringBuilder resultpS);

        [DllImport("smsdll.dll",
                  EntryPoint = "App_Gateway_Resp",
                    CharSet = CharSet.Ansi,
                    CallingConvention = CallingConvention.StdCall)]
        public static extern int App_Gateway_Resp(StringBuilder msgid, StringBuilder gateway_resp);

        [DllImport("smsdll.dll",
          EntryPoint = "App_ActiveTest",
            CharSet = CharSet.Ansi,
            CallingConvention = CallingConvention.StdCall)]
        public static extern int App_ActiveTest(StringBuilder active_resp);
        string content;
        string phonenumber;
        public SendSMS()
        { }
        public SendSMS(string Content,string PhoneNumber)
        {
            this.content = Content;
            this.phonenumber=PhoneNumber;
        }
        public void Send()
        {
            string Path = "D:\\";
            string strlog = "123";
            int ret = App_SetIniPath(Path);
            if (ret < 0)
            {
                StreamWriter sw1 = File.AppendText(@"D:\test.txt");
                sw1.WriteLine("发送失败--配置地址不对" + DateTime.Now);
                sw1.Close();
                return;
            }
            else
            {
                socket = App_Bind();
                if (socket > 0)
                {
                    string service_id = "10";
                    string phoneNumbe = phonenumber.ToString();
                    string Number = "106573004009";
                    int remsg = App_Submit(service_id, phoneNumbe, Number, content);
                    if (remsg > 0)
                    {
                        strlog = "发送成功----" + phoneNumbe + "\n"+DateTime.Now;
                        StreamWriter sw = File.AppendText(@"D:\test.txt");
                        sw.WriteLine(strlog);
                        sw.Close();
                        Add(phoneNumbe, content, 1);
                    }
                    else
                    {
                        strlog = "发送失败----" + phoneNumbe + "\n";
                        StreamWriter sw = File.AppendText(@"D:\test.txt");
                        sw.WriteLine(strlog);
                        sw.Close();
                        Add(phoneNumbe, content, 0);
                    }
                }
            }
        }
        public MySqlDataReader GetList(DateTime ToDay)
        {
            MySqlParameter[] parameters = { 
                                        new MySqlParameter("PAuditingTime", MySqlDbType.DateTime)
                                        };
            MySqlDataReader ds = DbHelperMySql.RunProcedureReader("GetSend", parameters);
            return ds;
        }
        public void Add(string PhoneNumber, string Content, int State)
        {
            MySqlParameter[] parameters = { 
                                   new MySqlParameter("PphoneNumber",MySqlDbType.VarChar,40),
                                   new MySqlParameter("Pcontent",MySqlDbType.VarChar,1000),
                                   new MySqlParameter("PState",MySqlDbType.Int32,4)
                                          };
            DbHelperMySql.RunProcedure("SendLog_Add", parameters);
        }
    }
}
